'''
pysqpyfia.py

Copyright 2009 Xavier Mendez Navarro aka Javi

This file is part of pysqlin

pysqlin is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

pysqlin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with pysqlin; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'''

import logging
import re

from framework.settings import Settings
from framework.myexceptions import MyException
from framework.queries import Database
from framework.myhttp import InjectionData
from framework.settings import Settings
from framework.interfaces import IPlugin
from framework.baseclass import BPlugin
from lib.importer import Importer

from sqPyfia import sqPyfia
from reqresp import Request

class PluginSqpyfia(Importer, IPlugin):
    """Launchs and controls the injection threads"""

    def __init__(self, api):
	BPlugin.__init__(self, api)

	self.__logger = logging.getLogger('plugins.auxiliary.scanner.sqpifya')

    def load(self, api):
	return self

    def name(self): return "sqpyfia"
    def description(self): 
	return """
	Automatizes the work of detecting blind SQL Injection vulnerabilities.

	* It uses SqPyfia plugin from deepbit\'s ProxyStrike (http://code.google.com/p/proxystrike/).
	"""

    def parameters(self): 
	a = dict(
		threads = ('10', 'Number of concurrent threads')
	)
	a.update(super(PluginSqpyfia, self).parameters())

	return a

    def commands(self): 
	return (('run', 'Perfom scan', 'run', [], self.cmd_scan),)

    def init(self):
	pass

    def transform_result(self, result):
	l = []
	url, all_sqli = result
	data = self.get_session_data()

	for var, method, itype, database, dberror in all_sqli:
	    db = self.dbpstrike_to_dbpysqlin(database)
	    dberror = self.dbpstrike_to_dbpysqlin(dberror)
	    l.append( (url, data[InjectionData.POST_DATA], data[InjectionData.COOKIE], var, method, itype, db, dberror) )

	return l

    def cmd_scan(self, **event):
	#self.set_results(['http://test.acunetix.com/AJAX/infotitle.php', [['id', 'POST', 'Unescaped Injection', 'MySQL', 'MySQL']]])
	#self.set_results(['http://testasp.acunetix.com/showforum.asp?id=1', [['id', 'GET', 'Unescaped Injection', 'MS Sql Server', None]]])
	#['http://localhost/inject.php?kk=1&id=1', [['id', 'GET', 'Unescaped Injection', 'MySQL', 'MySQL'], ['kk', 'GET', 'Unescaped Injection', 'MySQL', 'MySQL']]]
	data = self.get_session_data()

	a = Request()
	a.setUrl(data['url'].encode('utf-8'))
	a.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)")

	if data['post_data']:
	    a.setPostData(data['post_data'].encode('utf-8'))

	if data['cookie']:
	    a.addHeader("Cookie", data['cookie'].encode('utf-8'))

	proxy = Settings().get(Settings.SEC_HTTP, Settings.PROXY)
	if proxy: a.setProxy(proxy.encode('utf-8'))

	# log to console
	logger = logging.getLogger('sqpyfia')
	console = logging.StreamHandler()
	console.setLevel(logging.DEBUG)
	formatter = logging.Formatter('%(name)-7s: %(message)s')
	console.setFormatter(formatter)
	logger.addHandler(console)

	attacker = sqPyfia(a, logger=logger)
	attacker.setThreaded(int(data['threads']))
	attacker.launch()

	result = attacker.getRAWResults()
	if result is not None:
	    self.print_msg(attacker.getTXTResults())
	    self.sqlimport(
		#self.choose(self.transform_result(result))
		self.sqlimport_all(self.transform_result(result))
	    )
	else:
	    return "No injection found"

def load(api):
    return  PluginSqpyfia(api)
